package com.lauor.test.service.impl;

import com.lauor.smpedr.param.OptEnum;
import com.lauor.smpedr.param.SqlArgMap;
import com.lauor.smpedr.param.SqlParam;
import com.lauor.smpedr.session.SqlSession;
import com.lauor.smpedr.session.SqlSessionFactory;
import com.lauor.test.entity.User;
import com.lauor.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
    public int createUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int effectRows = sqlSession.insert(User.class, user);
        //回滚事务
//        if (true){
//            throw new RuntimeException("forbidding create exception");
//        }
        return effectRows;
    }

    @Override
    public List<User> queryAll(int start, int pageSize) {
        SqlSession sqlSession = sqlSessionFactory.openSession();

        SqlParam sqlParam = new SqlParam(start, pageSize);
        sqlParam.setOrderBy("create_time desc");
//        sqlParam.setGroupBy("id");
//        sqlParam.setHaving("id > 10");
        return sqlSession.selectList(User.class, null, sqlParam);

//        return sqlSession.selectList("user", User.class, null, sqlParam);

        //自定义sql查询
//        SqlArgMap<Integer> sqlArgMap = new SqlArgMap<>(4);
//        sqlArgMap.put("id", OptEnum.GT, 10);
//        return sqlSession.selectList("select * from user where id > #{id} limit 0, 10", User.class, sqlArgMap);
    }

    @Override
    public List<User> queryByName(String name) {
        SqlArgMap<String> argMap = new SqlArgMap<>(4);
        argMap.put("name", OptEnum.LIKE, OptEnum.LIKE.buildLikeParam("name"));

        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession.selectList(User.class, argMap, null);
    }

    @Override
    public int updateUser(User user, int id) {
        SqlArgMap<Integer> argMap = new SqlArgMap<>(4);
        argMap.put("id" , id);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession.update(user, argMap);
    }

    @Override
    public int deleteUserById(int id) {
        SqlArgMap<Integer> argMap = new SqlArgMap<>(4);
        argMap.put("id" , id);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession.delete(User.class, argMap);
    }
}
